<!-- 登录与注册 -->
<template>
  <view class="normal-login-container">
    <view class="logo-content align-center justify-center flex">
      <image style="width: 100rpx;height: 100rpx;" :src="globalConfig.appInfo.logo" mode="widthFix">
      </image>
      <text class="title">智慧食堂{{ isLogin ? "登录" : "注册" }}</text>
    </view>
    <view class="login-form-content">
      <view class="input-item flex align-center">
        <view class="iconfont icon-user icon"></view>
        <input v-model="loginForm.username" class="input" type="text" placeholder="请输入账号" maxlength="30" />
      </view>
      <view class="input-item flex align-center">
        <view class="iconfont icon-password icon"></view>
        <input v-model="loginForm.password" type="password" class="input" placeholder="请输入密码" maxlength="20" />
      </view>
      <view v-if="!isLogin" class="input-item flex align-center">
        <view class="iconfont icon-password icon"></view>
        <input v-model="loginForm.rePassword" type="password" class="input" placeholder="确认密码" maxlength="20" />
      </view>
      <view class="select_school" v-if="!isLogin" @click="selectSchool">{{ schoolSelect || '请选择学校' }}</view>
      <!-- <view v-if="!isLogin" class="code flex">
        <view class="input-item flex align-center" style="width: 60%;margin: 0px;">
          <view class="iconfont icon-code icon"></view>
          <input v-model="loginForm.code" type="number" class="input" placeholder="请输入验证码" maxlength="4" />
        </view>
        <button class="getCode">获取验证码</button>
      </view> -->
      <view class="action-btn">
        <button v-if="isLogin" @click="handleLogin" class="login-btn cu-btn block bg-blue lg round">登录</button>
        <button v-if="!isLogin" @click="handleRegister" class="login-btn cu-btn block bg-blue lg round">注册</button>
        <button @click="change" class="login-change cu-btn block lg round ">{{ isLogin ? "去注册" : "去登录" }}</button>
      </view>
    </view>

    <view class="xieyi text-center">
      <text class="text-grey1">登录即代表同意</text>
      <text @click="handleUserAgrement" class="text-blue">《用户协议》</text>
      <text @click="handlePrivacy" class="text-blue">《隐私协议》</text>
    </view>
    <up-picker :show="showSchool" :columns="schoolColumns" keyName="name" @confirm="confirm"
      @cancel="cancel"></up-picker>
  </view>
</template>

<script setup>
import modal from '@/plugins/modal'
import { getCodeImg } from '@/api/login'
import { ref, reactive } from "vue";
import config from '@/config.js'
import useUserStore from '@/store/modules/user'
import { register, login } from '@/api/login'
import { getWxCode } from '@/utils/geek';
import { wxLogin } from '@/api/oauth';
import { setToken } from '@/utils/auth';
import { getUserInfo } from "@/api/user/index";
import { getAllSchoolInfo } from "@/api/school/index";
const userStore = useUserStore()
const codeUrl = ref("");
const useWxLogin = ref(false); // 是否使用微信登录
const globalConfig = ref(config);
let isLogin = ref(true);
let loginForm = ref({
  username: "",
  password: "",
  rePassword: "",
  schoolId: "",
  schoolName: "",
});

if (useWxLogin.value) {
  getWxCode().then(res => {
    console.log(res);
    wxLogin('miniapp', res).then(res => {
      if (res.token != null) {
        setToken(res.token);
        loginSuccess()
      }
    });
  })
}


// 获取图形验证码
function getCode() {
  getCodeImg().then(res => {
    captchaEnabled.value = res.captchaEnabled === undefined ? true : res.captchaEnabled
    if (captchaEnabled.value) {
      codeUrl.value = 'data:image/gif;base64,' + res.img
      loginForm.value.uuid = res.uuid
    }
  })
};

// 登录按钮点击事件
async function handleLogin() {
  if (loginForm.value.username === "") {
    modal.msgError("请输入您的账号")
  } else if (loginForm.value.password === "") {
    modal.msgError("请输入您的密码")
  } else {
    modal.loading("登录中，请耐心等待...")
    login({ username: loginForm.value.username, password: loginForm.value.password }).then(res => {
      if (res.code == 200) {
        modal.msgSuccess("登录成功")
        // 去首页之前先将用户的id存起来
        userStore.userId = res.userId
        getUserInfo({ userId: res.userId || '' }).then(res => {
          userStore.getInfo(res.userInfo)
        })
        console.log("userStore.userId", userStore.userId);
        //登录成功去往首页
        uni.switchTab({
          url: '/pages/index'
        });
      } else {
        modal.msgError(res.message)
      }
    }).catch(err => {
      modal.closeLoading()
      modal.msgError("登录失败")
    })
  }
};

// 注册按钮点击事件
async function handleRegister() {
  if (loginForm.value.username === "") {
    modal.msgError("请输入您的账号")
  } else if (loginForm.value.password === "") {
    modal.msgError("请输入您的密码")
  } else if (loginForm.value.rePassword === "") {
    modal.msgError("请再次输入您的密码")
  } else if (loginForm.value.password !== loginForm.value.password) {
    modal.msgError("两次输入的密码不同")
  } else if (loginForm.value.schoolId === '') {
    modal.msgError("请选择学校")
  } else {
    modal.loading("注册中，请耐心等待...")
    console.log('loginForm.value: ', loginForm.value);

    setTimeout(() => {
      register({
        username: loginForm.value.username,
        password: loginForm.value.password,
        schoolId: loginForm.value.schoolId,
        schoolName: loginForm.value.schoolName
      }).then(res => {
        modal.closeLoading()
        console.log(res);
        if (res.code == 200) {
          modal.msgSuccess("注册成功")
          isLogin.value = true
        } else {
          modal.msgError(res.message)
        }
      }).catch(err => {
        modal.closeLoading()
        modal.msgError("注册失败")
      })
    }, 1500);
  }
};

/**
 * 查询所有学校数据
 */
getAllSchoolInfo().then(res => {
  console.log(res);
  if (res.code == 200) {
    schoolColumns = [res.schoolData]
  }
})

/**
 * 选择需学校
 */
let showSchool = ref(false);
let schoolSelect = ref('')
let schoolColumns = reactive([]);
function selectSchool() {
  showSchool.value = true
}

function confirm(val) {
  console.log('val: ', val);
  showSchool.value = false
  schoolSelect.value = val.value[0].name
  loginForm.value.schoolId = val.value[0]._id
  loginForm.value.schoolName = val.value[0].name
}

function cancel() {
  showSchool.value = false
}


// 密码登录
async function pwdLogin() {
  // userStore.login(loginForm.value).then(() => {
  //   modal.closeLoading()
  //   loginSuccess()
  // }).catch(() => {
  //   if (captchaEnabled.value) {
  //     modal.closeLoading()
  //     getCode()
  //   }
  // })
};

function loginSuccess(result) {
  // 设置用户信息
  userStore.getInfo().then(res => {
    uni.switchTab({
      url: '/pages/index'
    });
  })
}

// 切换登录和注册状态
function change() {
  isLogin.value = !isLogin.value
  loginForm.value = {
    username: "",
    password: "",
    rePassword: "",
    schoolId: "",
    schoolName: "",
  };
}

// 隐私协议
function handlePrivacy() {
  let site = globalConfig.value.appInfo.agreements[0];
  uni.navigateTo({
    url: `/pages/common/webview/index?title=${site.title}&url=${site.url}`
  });
};
// 用户协议
function handleUserAgrement() {
  let site = globalConfig.value.appInfo.agreements[1]
  uni.navigateTo({
    url: `/pages/common/webview/index?title=${site.title}&url=${site.url}`
  });
};

// getCode();
</script>

<style lang="scss">
page {
  background-color: #ffffff;
}

.normal-login-container {
  width: 100%;

  .logo-content {
    width: 100%;
    font-size: 21px;
    text-align: center;
    padding-top: 15%;

    image {
      border-radius: 4px;
    }

    .title {
      margin-left: 10px;
    }
  }

  .login-form-content {
    text-align: center;
    margin: 20px auto;
    margin-top: 15%;
    width: 80%;

    .input-item {
      margin: 20px auto;
      background-color: #f5f6f7;
      height: 45px;
      border-radius: 20px;

      .icon {
        font-size: 38rpx;
        margin-left: 10px;
        color: #999;
      }

      .input {
        width: 100%;
        font-size: 14px;
        line-height: 20px;
        text-align: left;
        padding-left: 15px;
      }

    }

    .login-btn {
      margin-top: 30px;
      height: 45px;
    }

    .login-change {
      margin-top: 10px;
      height: 45px;
    }

    .code {
      display: flex;
      align-items: center;

      .getCode {
        font-size: 12px;
        height: 30px;
        line-height: 30px;
      }
    }

    .xieyi {
      color: #333;
      margin-top: 20px;
    }

    .login-code {
      height: 38px;
      float: right;

      .login-code-img {
        height: 38px;
        position: absolute;
        margin-left: 10px;
        width: 200rpx;
      }
    }
  }

  .select_school {
    width: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    color: $uni-text-color-grey;
    border-bottom: 1rpx solid $uni-text-color-grey;
  }
}
</style>
